<template>
  <div>
    <button class="sub-btn" @click=handleSub>-</button>
    <input type="text" class="count-box" :value="value" @change="handleChange">
    <button class="add-btn" @click="handleAdd">+</button>
  </div>
</template>

<script>
export default {
  name: 'CountBox',
  props: {
    value: {
      type: Number,
      require: true
    }
  },
  data () {
    return {
    }
  },
  methods: {
    handleSub () {
      if (this.value === 1) {
        return
      }
      this.$emit('handlechange', this.value - 1)
    },
    handleAdd () {
      this.$emit('handlechange', this.value + 1)
    },
    handleChange (e) {
      const num = Number(e.target.value)
      if (isNaN(num) || num < 1) {
        e.target.value = this.value
      } else {
        this.$emit('handlechange', num)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.sub-btn,
.add-btn {
  padding: 5px 10px;
  background: #efefef;
  border: none;
  margin: 0 10px;
}

.count-box {
  display: inline-block;
  width: 40px;
  background: #efefef;
  padding: 5px 0;
  border: none;
  text-align: center;
}
</style>
